    //
//  WifiViewController.m
//  WifiTransport
//
//  Created by apple on 10-11-23.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "WifiViewController.h"
#import "httpServer.h"
#import "Reachability.h"
//#import "Sqlite3Manage.h"

@implementation WifiViewController
@synthesize m_OperationPath;
@synthesize m_Delegate;
// load file list  HTTPUploadingProgressNotification
- (void)load_fileList
{
	[_fileList removeAllObjects];
	NSString* docDir = [NSString stringWithFormat:@"%@", m_OperationPath];
	NSArray *dirArray = [NSArray arrayWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:docDir error:nil]];
	for(NSString *pname in dirArray)
	{
		NSLog(@"%@", pname);
		[_fileList addObject:pname];
	}
}

/// 网络是否是通的
- (BOOL)networkAvailable {
    Reachability *r = [Reachability reachabilityForInternetConnection];
    int tStatus = [r currentReachabilityStatus];
    if (tStatus == kReachableViaWiFi) {
        return YES;
    }
    return NO;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    [super viewDidLoad];
	
	UIImageView *bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"wifi_bg.png"]];
	[self.view addSubview:bg];
	[bg release];
	UILabel *seviceLabe = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 80, 30)];
	seviceLabe.backgroundColor = [UIColor clearColor];
	seviceLabe.text = @"开启服务:";  
	[self.view addSubview:seviceLabe];
	[seviceLabe release];
	
	_pSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(105, 52, 50, 30)];
	[_pSwitch setOn:NO];
	_isServerRunning = NO;
	[_pSwitch addTarget:self action:@selector(toggleService:) forControlEvents:UIControlEventValueChanged];
	[self.view addSubview:_pSwitch];
	
	UILabel *url = [[UILabel alloc] initWithFrame:CGRectMake(20, 90, 80, 30)];
	url.backgroundColor = [UIColor clearColor];
	url.text = @"服务地址:";
	[self.view addSubview:url];
	[url release];
	
	_urlLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 90, 215, 30)];
	_urlLabel.backgroundColor = [UIColor clearColor];
	[self.view addSubview:_urlLabel];
	
	UILabel *help = [[UILabel alloc] initWithFrame:CGRectMake(20, 140, 300, 230)];
	help.numberOfLines = 20;
	help.backgroundColor = [UIColor clearColor];
	help.text = @"帮助：\r1.将电脑通过无线网卡连接至一个无线网络\
						\r2.在该设备的设置中打开WIFI开关，连接至同一无线网络\
						\r3.打开上面的“开启服务”按钮，此时“服务地址”处会显示字符\
						\r4.打开电脑端的浏览器，在地址栏中输入上述服务地址\
						\r5.选择文件后点击上传，即可将电脑中的文件传入该设备";
	[self.view addSubview:help];
	[help release];
	UIBarButtonItem* tDoneBar = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(wifiTransOver)];
    self.navigationItem.rightBarButtonItem = tDoneBar;
    [tDoneBar release];
    
	//wifi
	_fileList = [[NSMutableArray alloc] init];
	[self load_fileList];
	
	// set up the http server
	_httpServer = [[HTTPServer alloc] init];
	[_httpServer setType:@"_http._tcp."];	
	[_httpServer setPort:9090];
	[_httpServer setName:@"CocoaWebResource"];
	[_httpServer setupBuiltInDocroot];
	_httpServer.fileResourceDelegate = self;	
}


- (void)viewWillAppear:(BOOL)animated {
	
	UINavigationController *nv = (UINavigationController *)[self navigationController];
	[nv.navigationBar setBarStyle:UIBarStyleBlack];
	[nv setNavigationBarHidden:NO animated:NO];
	
	[self load_fileList];

	self.title = @"Wifi传输";
	
	[super viewWillAppear:animated];
    
    NSNotificationCenter* tNotficationC = [NSNotificationCenter defaultCenter];
    [tNotficationC addObserver:self selector:@selector(updateProgress:) name:HTTPUploadingProgressNotification object:nil];
    [tNotficationC addObserver:self selector:@selector(startProgress:) name:HTTPUploadingStartNotification object:nil];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
    
    NSNotificationCenter* tNotficationC = [NSNotificationCenter defaultCenter];
    [tNotficationC removeObserver:self];
    
    if (_isServerRunning) 
    {
        NSLog(@"wifi stop");
        [_httpServer stop];
        [_urlLabel setText:@""];
        _isServerRunning = NO;
    }
}
- (void) backToRoot
{
	[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	_httpServer.fileResourceDelegate = nil;
	[_httpServer release];
	[_fileList release];
	[_urlLabel release];
	[_pSwitch release];
    [m_OperationPath release];
    [p_AlertPro release];
    [p_Progress release];
    [super dealloc];
}


-(void) updateProgress:(NSNotification*) f_Pro
{
    float tValue = [((NSString*)f_Pro.object) floatValue];
    [p_Progress setProgress:tValue animated:YES];
}

-(void) startProgress:(NSNotification*) f_FileName
{
    NSString* tUpFileName= f_FileName.object;
    if (p_AlertPro) {
        [p_AlertPro dismissWithClickedButtonIndex:-1 animated:YES];
        [p_AlertPro release];
        p_AlertPro =nil;
        [p_Progress release];
        p_Progress =nil;
    }
    p_AlertPro = [[UIAlertView alloc] initWithTitle:@"wifi上传文件" 
                                                        message:[NSString stringWithFormat:@"文件：%@正在上传",tUpFileName]
                                                       delegate:self 
                                              cancelButtonTitle:@"" 
                                              otherButtonTitles: nil];  
    [p_AlertPro show];
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    for (id object in [alertView subviews]) {
        NSLog(@"%@",[object description]);
        if ([object isKindOfClass:[UIButton class]]) {
            UIButton* tBtt = (UIButton*)object;
            tBtt.hidden =YES;
            if (p_Progress) {
                [p_Progress release];
                p_Progress =nil;
            }
            CGRect aframe =tBtt.frame;
            //aframe.origin.y -=10;
            p_Progress = [[UIProgressView alloc] initWithFrame:aframe];
            [alertView addSubview:p_Progress];
        }
    }
}

-(void) finishProgress
{
    if (p_AlertPro) {
        [p_AlertPro dismissWithClickedButtonIndex:0 animated:YES];
        [p_AlertPro release];
        p_AlertPro = nil;
        [p_Progress release];
        p_Progress =nil;
    }
}

#pragma mark actions
- (void)toggleService:(id)sender
{
	NSError *error;
	if ([(UISwitch*)sender isOn])
	{
		if (!_isServerRunning) 
		{
			NSLog(@"wifi start");
			_isServerRunning = [_httpServer start:&error];
			if(!_isServerRunning)
			{
				NSLog(@"Error starting HTTP Server: %@", error);
			}	
			[_urlLabel setText:[NSString stringWithFormat:@"http://%@:%d", [_httpServer hostName], [_httpServer port]]];
			_isServerRunning = YES;
		}
	}
	else
	{
		if (_isServerRunning) 
		{
			NSLog(@"wifi stop");
			[_httpServer stop];
			[_urlLabel setText:@""];
			_isServerRunning = NO;
		}
	}
}

#pragma mark WebFileResourceDelegate
// number of the files
- (NSInteger)numberOfFiles
{
	return [_fileList count];
}

// the file name by the index
- (NSString*)fileNameAtIndex:(NSInteger)index
{
	return [_fileList objectAtIndex:index];
}

// provide full file path by given file name
- (NSString*)filePathForFileName:(NSString*)filename
{
	NSString* docDir = [NSString stringWithFormat:@"%@",m_OperationPath];
	return [NSString stringWithFormat:@"%@/%@", docDir, filename];
}

// handle newly uploaded file. After uploading, the file is stored in
// the temparory directory, you need to implement this method to move
// it to proper location and update the file list.
- (void)newFileDidUpload:(NSString*)name inTempPath:(NSString*)tmpPath
{
    [self finishProgress];
	if (name == nil || tmpPath == nil || [name isEqualToString:@""])
		return;
	NSLog(@"name%@",name);
	NSLog(@"%@",tmpPath);
    
    NSString *format = [name substringFromIndex:[name length] - 4];
	format = [format lowercaseString];
//	if (![format isEqualToString:@".mp3"]) 
//	{
//		//不符合条件进行删除处理
//		NSFileManager *fm = [NSFileManager defaultManager];
//		NSError *error;
//		if(![fm removeItemAtPath:tmpPath error:&error])
//		{
//			NSLog(@"%@ can not be removed because:%@", tmpPath, error);
//		}		
//		return;
//	}
	NSString *path = [NSString stringWithFormat:@"%@/%@", m_OperationPath, name];
	NSFileManager *fm = [NSFileManager defaultManager];
	NSError *error;
	if (![fm moveItemAtPath:tmpPath toPath:path error:&error])
	{
		NSLog(@"can not move %@ to %@ because: %@", tmpPath, path, error );
		if(![fm removeItemAtPath:tmpPath error:&error])
		{
			NSLog(@"%@  can not be removed because:%@", tmpPath, error);
		}		
	}
	else 
	{
		[self load_fileList];
		//执行外部添加回调
        if (m_Delegate) {
            [m_Delegate performSelector:@selector(fileAddByWifiFinish:) withObject:path];
        }
	}
}

//SQL语法组合
-(NSString*) comSqlStr:(NSString*)str{
	return [NSString stringWithFormat:@"'%@'",str];
}

// implement this method to delete requested file and update the file list
- (void)fileShouldDelete:(NSString*)fileName
{
	NSString *path = [self filePathForFileName:fileName];
	NSFileManager *fm = [NSFileManager defaultManager];
	NSError *error;
	if(![fm removeItemAtPath:path error:&error])
	{
		NSLog(@"%@ can not be removed because:%@", path, error);
	}
	else 
	{
		//执行外部删除回调
        if (m_Delegate) {
            [m_Delegate performSelector:@selector(fileDeleteByWifiFinish:) withObject:path];
        }
	}
	[self load_fileList];
}

-(BOOL)deleteBook :(NSString *)bookpath
{
	if (bookpath != nil && ![bookpath isEqualToString:@""]) 
	{
		NSFileManager *fm = [NSFileManager defaultManager];
		NSError *error;
		if(![fm removeItemAtPath:bookpath error:&error])
		{
			NSLog(@"%@ can not be removed because:%@", bookpath, error);
			return FALSE;
		}	
		[self load_fileList];
		return TRUE;
	}
	return FALSE;
}

-(void) wifiTransOver
{
    [self dismissModalViewControllerAnimated:YES];
}


@end
